var init;
var width
window.onload=function(){
	width = $("#textName").outerWidth();
	console.log(width);
    updateUserStatus(sessionStorage['userId'], sessionStorage['userName']);
    $("#userId").val(sessionStorage['userId']);
    init = getFormJson;
    var currentPage=1;
    var timer;
    if(sessionStorage['token']){
        getFormJson();
    }
    getsrcLen();

    //拿取源语言
    function getsrcLen(){
        $.ajax({
            url:URL_ip+"/getSrcLan",
            type:"post",
            error: function(error) {
                //失败原因
            },
            success:function(data){
                if(data.code==0){
                    for(var i=0;i<data.data.length;i++){
                        $("#srcLan").append('<option id="'+data.data[i].languageId+'" value="'+data.data[i].language+'">'+data.data[i].language+'</option>');
                    }
                    getdestLen();
                }

            }
        })
    }

    function getdestLen(){
        var data={
            "languageId":$("#srcLan > option").eq(1).attr('id')
        };
        $.ajax({
            url:URL_ip+"/getDestLan",
            type:"post",
            contentType: 'application/json',
            dataType: 'json',
            data:JSON.stringify(data),
            error: function(error) {
                //失败原因
            },
            success:function(data){
                if(data.code==0){
                    for(var i=0;i<data.data.length;i++){
                        $("#destLan").append('<option id="'+data.data[i].languageId+'" value="'+data.data[i].language+'">'+data.data[i].language+'</option>');
                    }
                }
                if(data.code==1){

                }
            }
        })
    }
    $(".showPagePaging").click(function () {
    });
    $("#clickAll").click(function(){
        if($("#clickAll").text() == "全选"){
            $("#clickAll").text("取消全选");
            // downloadList.length = 0;
            $("input[type=checkbox]").prop('checked', true);
            var box = $("input[type=checkbox]");
            for(var i = 0; i < box.length;i++){
                downloadList.push($(box[i]).attr("data-value"));
            }
        } else if($("#clickAll").text() == "取消全选"){
            $("#clickAll").text("全选");
            var checkArray = $("input[type='checkbox']:checked");
            console.log(checkArray);
            for (var i = 0;i<checkArray.length;i++){
                var id = $(checkArray[i]).attr("data-value");
                for(var j=0;j < downloadList.length;j++){
                    if(downloadList[j] == id){
                        downloadList.splice(j, 1);
                    }
                }
                console.log(id);
            }
            $("input[type=checkbox]").prop('checked', false);
        }
        console.log(downloadList);
    });
    $("#downAll").click(function(){
        console.log(downloadList);
        if(downloadList.length == 0){
            alert("请选择文件");
        } else {
            var orderIdS = "";
            for(var i = 0;i < downloadList.length; i++){
                orderIdS = orderIdS + "," + downloadList[i];
            }
            if (orderIdS.substr(0,1)==','){
                orderIdS = orderIdS.substr(1);
            }
            location.href = URL_ip+'/getZipFile?orderIdS='+orderIdS+"&userId="+sessionStorage['userId'];

        }
    });
    $("#deleteAll").click(function(){
        console.log(downloadList);
        if(downloadList.length == 0){
            alert("请选择文件")
        } else {
            for(var i = 0;i < downloadList.length; i++){
                deleteAllDoc(downloadList[i]);
            }
            downloadList.length = 0;
        }
    });
    $("#destLan").change(function(){
        if($(this).attr('id')){
            getFormJson();
        }
    })
    $("#srcLan").change(function(){
        if($(this).attr('id')){
            getFormJson();
        }
    })
    $("#File_list > li").click(function(){
        clearTimeout(timer);
        var that=this;
        $("#File_list > li").each(function(){
            $(this).removeClass("cur");
        })
        $(that).addClass('cur');
        getFormJson();
    })
    $("#search").click(function(){
        getFormJson();
    })
    $("input[name='docName']").keyup(function(){
        if(event.keyCode ==13){
            getFormJson();
        }

    })
    //文档列表初始化--
    function initiList(data,key){
        var fileData=data;
        $("#File_list > li").each(function(){
            if($(this).hasClass('cur')&&$(this).attr('key')){
                data.orderStatus=$(this).attr('key');
            }
            if($(this).hasClass('cur')&&$(this).attr('id')){
                data.orderId=$(this).attr('id');
            }
        })
        $.ajax({
            url:URL_ip+'/searchDoc',
            type:'post',
            contentType: 'application/json',
            dataType: 'json',
            data:JSON.stringify(data),
            beforeSend: function(request) {
                $('#none_info').text('');
                request.setRequestHeader("X-OAUTH-TOKEN", sessionStorage['token']);
                if(window.location.search&&$("#File_list > li").eq(0).hasClass('cur')&&$("#File_list > li").eq(0).attr('id')){
                }else{
                    $('#documentList').html('');
                }
                if(!key){
                    $("#loading_list").css('display','inline');
                }
                if($('.showPagePaging')){
                    $('.showPagePaging').hide();
                }
            },
            error: function(XMLHttpRequest) {
                //失败原因
                timeOut_error(XMLHttpRequest);
            },
            success:function(data){
                //window.location.search存在且cur有id
                if(window.location.search&&$("#File_list > li").eq(0).hasClass('cur')&&$("#File_list > li").eq(0).attr('id')){
                    if($('.showPagePaging')){
                        $('.showPagePaging').hide();
                    }
                    latestData(data,key);
                }else{
                    initdata(data);
                }
            }
        })
    }
    function latestData(data,key){
        //console.log(data)
        $("#loading_list").css('display','none');
        if(!key){
            $("#documentList").html('');
            for(var i=0;i<data.data.length;i++){
                var index=i+1;
                var status;
                var progress;
                var checkbox;
                if(data.data[i].status=="翻译完成"){
                    status='<a type="button" class="btn btn-info"  href="' + encodeURI(data.data[i].fileDownloadUrl) + '" download="" downid="'+data.data[i].lId+'">下载</a>';
                    let deleteButton = '<span type="button" class="deleteButton" value="'+data.data[i].lId+'" onclick="deleteDoc(this)">删除</span>';
                    status = status + deleteButton;
                    checkbox='<input type="checkbox" style="margin-right: 5px" onchange="haveDown(this)" data-value="'+data.data[i].lId+'"/>';
                    progress='翻译完成';
                }else if(data.data[i].status=="翻译中"){
                    status='';
                    progress='翻译中';
                    let deleteButton = '<span type="button" class="deleteButton" value="'+data.data[i].lId+'" onclick="deleteDoc(this)">删除</span>';
                    status = status + deleteButton;
                    checkbox='<input type="checkbox" style="margin-right: 5px" onchange="haveDown(this)" data-value="'+data.data[i].lId+'"/>';
                    //timer=setTimeout(function(){getSpeedProgress(data.data[i].docId,i)},1000);
                    getSpeedProgress(data.data[i].lId,i);
                }else if(data.data[i].status=="等待翻译"){
                    checkbox='<input type="checkbox" style="margin-right: 5px" onchange="haveDown(this)" data-value="'+data.data[i].lId+'"/>';
                    status='';
                    let deleteButton = '<span type="button" class="deleteButton" value="'+data.data[i].lId+'" onclick="deleteDoc(this)">删除</span>';
                    status = status + deleteButton;
                    progress='等待翻译';
                }else if(data.data[i].status=="待支付"){
                    checkbox='<input type="checkbox" style="margin-right: 5px" onchange="haveDown(this)" data-value="'+data.data[i].lId+'"/>';
                    status='<a type="button" class="btn btn-warning" id="'+data.data[i].orderId+'" onclick="toPay(this)">支付</a>';
                    let deleteButton = '<span type="button" class="deleteButton" value="'+data.data[i].lId+'" onclick="deleteDoc(this)">删除</span>';
                    status = status + deleteButton;
                    progress='';
                }
                var html='<tr>'+
                    '<td>'+checkbox+index+'</td>'+
                    '<td>'+data.data[i].orderId+'</td>'+
                    '<td title='+data.data[i].filename+'>'+'<p class="textp">'+data.data[i].filename+'</p>'+'</td>'+
                    '<td>'+data.data[i].transTime+'</td>'+
                    '<td>'+data.data[i].wordNum+'</td>'+
                    '<td>'+data.data[i].lan+'</td>'+
                    '<td>'+progress+'</td>'+
                    '<td>'+status+'</td>'+
                    '</tr>';
                $('#documentList').append(html);
                $(".textp").css("width",width + "px");
            }
        }else{
            for(var i=0;i<data.data.length;i++){
                $("#documentList > tr").eq(i).children('td').eq(6).html(data.data[i].status);
                if(data.data[i].status=="翻译完成"){
                    var status='<a type="button" download="" class="btn btn-info" href="' + encodeURI(data.data[i].fileDownloadUrl) + '" downid="'+data.data[i].lId+'">下载</a>'
                    let deleteButton = '<span type="button" class="deleteButton" value="'+data.data[i].lId+'" onclick="deleteDoc(this)">删除</span>';
                    status = status + deleteButton;
                    checkbox='<input type="checkbox" style="margin-right: 5px" onchange="haveDown(this)" data-value="'+data.data[i].lId+'"/>';
                    $("#documentList > tr").eq(i).children('td').eq(7).html(status);
                    $("#documentList > tr").eq(i).children('td').eq(6).css('color','#333');
                }else if(data.data[i].status=="翻译中"){
                    getSpeedProgress(data.data[i].lId,i);
                }
            }
        }

    }

    function initdata(data){
        $("#loading_list").css('display','none');
        $("#none_info").remove();
        if(data.code==0){
            var status;
            var progress;
            var checkbox;
            var  file_data=new Array();
            var num=1;
            var page=5;
            if(data.data.length==0){
                $(".showPagePaging").css('display','none');
                $('<p class="none_info" id="none_info">暂无数据</p>').insertAfter($("#idDdata"));
            }else{
                $(".showPagePaging").css('display','block');
                for(var i=0;i<data.data.length;i++){
                    if(i<=num*page-1){
                        if(i==(num-1)*page){
                            file_data[num-1]=new Array();
                        }
                        file_data[num-1].push(data.data[i]);
                        if(i==num*page-1){
                            num++;
                        }
                    }
                }
                $(".showPagePaging").simplePaging({
                    allPage:file_data.length,//总页数
                    showPage:9,//显示页数
                    startPage: 1,//第一页页码数字
                    initPage:sessionStorage['currentPage'],//加载完毕自动跳转到第n页(初始化激活页)
                    initPageClick:true,//每次页面加载完毕后，是否触发initPage页的绑定事件
                    first: "首页",//首页显示字符
                    last: "尾页",//尾页显示字符
                    prev: "«",//上一页显示字符
                    next: "»",//下一页显示字符
                    showTurnTo: false,//是否显示跳转按钮，true显示，false不显示
                    animateType: "animation",//过渡模式：动画“animation”、跳动“jumpy”、快速移动“fast”、正常速度移动“normal”、缓慢的速度移动“slow”、异常缓慢的速度移动“verySlow”
                    animationTime: 300,//animateType为animation时，动画过渡时间(ms)
                    callBack: function (num) {
                        currentPage=num;
                        sessionStorage['currentPage'] = currentPage;
                        console.log(currentPage);
                        $("#documentList").html('');
                        var data  = file_data[num-1];
                        for(var i=0;i<data.length;i++){
                            var index=(num-1)*page+i+1;
                            if(data[i].status=="待支付"){
                                checkbox='<input type="checkbox" style="margin-right: 5px" onchange="haveDown(this)" data-value="'+data[i].lId+'"/>';
                                //href跳到支付页
                                status='<a type="button" class="btn btn-warning" id="'+data[i].orderId+'" onclick="toPay(this)">支付</a>';
                                progress='';
                            }else if(data[i].status=="翻译完成"){
                                status='<a type="button" download="" class="btn btn-info" href="' + encodeURI(data[i].fileDownloadUrl) + '" downid="' + data[i].lId + '">下载</a>';
                                let deleteButton = '<span type="button" class="deleteButton" value="'+data[i].lId+'" onclick="deleteDoc(this)">删除</span>';
                                status = status + deleteButton;
                                progress='翻译完成';
                                checkbox='<input type="checkbox" style="margin-right: 5px" onchange="haveDown(this)" data-value="'+data[i].lId+'"/>';
                            }else if(data[i].status=="已支付"){
                                status='<a type="button" class="btn btn-info">已支付</a>';
                                progress='';
                            }else if(data[i].status=="翻译中"){
                                checkbox='<input type="checkbox" style="margin-right: 5px" onchange="haveDown(this)" data-value="'+data[i].lId+'"/>';
                                status='';
                                let deleteButton = '<span type="button" class="deleteButton" value="'+data[i].lId+'" onclick="deleteDoc(this)">删除</span>';
                                status = status + deleteButton;
                                progress='翻译中';
                            }else if(data[i].status=="等待翻译"){
                                checkbox='<input type="checkbox" style="margin-right: 5px" onchange="haveDown(this)" data-value="'+data[i].lId+'"/>';
                                status='';
                                let deleteButton = '<span type="button" class="deleteButton" value="'+data[i].lId+'" onclick="deleteDoc(this)">删除</span>';
                                status = status + deleteButton;
                                progress='等待翻译';
                                /*setTimeout(function(){initiList(fileData)},1000);*/
                            }
                            var html='<tr>'+
                                '<td>'+checkbox+index+'</td>'+
                                '<td>'+data[i].orderId+'</td>'+
                                '<td title='+data[i].filename+'>'+'<p class="textp">'+data[i].filename+'</p>'+'</td>'+
                                '<td>'+data[i].transTime+'</td>'+
                                '<td>'+data[i].wordNum+'</td>'+
                                '<td>'+data[i].lan+'</td>'+
                                '<td>'+progress+'</td>'+
                                '<td>'+status+'</td>'+
                                '</tr>';
                            $('#documentList').append(html);
                            $(".textp").css("width",width + "px");
                        }
                        $("#clickAll").text("全选");
                        // downloadList.length = 0;
                        for (var i = 0; i < downloadList.length; i++){
                            $('input[data-value='+downloadList[i]+']').prop('checked', true);
                        }
                        var checkLength = $("input[type='checkbox']").length;
                        var isCheckLength = $("input[type='checkbox']:checked").length;
                        if(isCheckLength == checkLength){
                            $("#clickAll").text("取消全选");
                        }
                    }
                })
                if($(".spPrev").length>1){
                    $(".spPrev").eq(0).remove();
                    $(".spFirst").eq(0).remove();
                    $(".spPage").eq(0).remove();
                    $(".spLast").eq(0).remove();
                    $(".spNext").eq(0).remove();
                }
            }

        }
        if(data.code==1){
            $(".showPagePaging").css('display','none');
            $('<p class="none_info" id="none_info">暂无数据</p>').insertAfter($("#idDdata"));
        }
    }
    //获取翻译中文件进度
    function getSpeedProgress(id,index){
        if(window.location.search&&$("#File_list > li").eq(0).hasClass('cur')&&$("#File_list > li").eq(0).attr('id')){
            var data={
                'docId':id.toString()
            }
            $.ajax({
                url:URL_ip+'/speedProgress/getSpeedProgress',
                type:'post',
                contentType: 'application/json',
                dataType: 'json',
                data:JSON.stringify(data),
                beforeSend: function(request) {
                    request.setRequestHeader("X-OAUTH-TOKEN", sessionStorage['token']);
                },
                error: function(XMLHttpRequest) {
                    //失败原因
                    timeOut_error(XMLHttpRequest);
                },
                success:function(data){
                    var progress=data.data.progress+'%';
                    $('#documentList > tr').eq(index).children('td').eq(6).html(progress);
                    $('#documentList > tr').eq(index).children('td').eq(6).css('color','#1262F4');
                    if(progress=='100%'){
                        getFormJson(true);
                    }else{
                        timer=setTimeout(function(){getSpeedProgress(id,index)},1000);
                    }
                }
            })
        }

    }
    function getFormJson(key) {  //frm：form表单的id
        var o = {};
        var a = $("#listForm").serializeArray();
        $.each(a, function() {
            if (o[this.name] === undefined&&this.value!== '') {
                o[this.name] = this.value;
            }
        });
        initiList(o,key);
    }
}
function toPay(obj){
    sessionStorage['orderId'] =$(obj).attr('id');
    window.location.href=Project_ip+'Information.html';
}
function deleteDoc(obj){
    let id = $(obj).attr('value');
    var data = {
        'docId':id.toString()
    };
    $.ajax({
        url:URL_ip+'/deleteDoc',
        type:'post',
        contentType: 'application/json',
        dataType: 'json',
        data:JSON.stringify(data),
        beforeSend: function(request) {
            request.setRequestHeader("X-OAUTH-TOKEN", sessionStorage['token']);
        },
        error: function(XMLHttpRequest) {
            //失败原因
            timeOut_error(XMLHttpRequest);
        },
        success:function(data){
            for (let i = 0 ;i < downloadList.length;i++){
                if(downloadList[i] == id){
                    downloadList.splice(i, 1);
                }
            }
            init();
        }
    })
}
function deleteAllDoc(docId){
    let id = docId;
    var data = {
        'docId':id.toString()
    };
    $.ajax({
        url:URL_ip+'/deleteDoc',
        type:'post',
        contentType: 'application/json',
        dataType: 'json',
        data:JSON.stringify(data),
        beforeSend: function(request) {
            request.setRequestHeader("X-OAUTH-TOKEN", sessionStorage['token']);
        },
        error: function(XMLHttpRequest) {
            //失败原因
            timeOut_error(XMLHttpRequest);
        },
        success:function(data){
            init();
        }
    })
}
const downloadList = [];
function haveDown(obj){
    var id = $(obj).attr("data-value");
    var boolean = $(obj).prop('checked');
    if(boolean){
        downloadList.push(id);
    } else {
        for(var i=0;i<downloadList.length;i++){
            if(downloadList[i] == id){
                downloadList.splice(i, 1);
            }
        }

    }
    var isCheckLength = $("input[type='checkbox']:checked").length;
    if(isCheckLength == 5){
        $("#clickAll").text("取消全选");
    } else {
        $("#clickAll").text("全选");
    }
    console.log(downloadList);
}



if(window.location.search){
    $("#File_list > li").each(function(){
        $(this).removeClass("cur");
    })
    var html='<li class="cur" id="'+sessionStorage["orderId"]+'">最新</li>';
    $("#File_list"). prepend(html);
}
